"use client";
import { createContext, useContext, useState, useEffect } from "react";
import Cookies from "js-cookie";
import axios from "axios";

// Create a context for the user
const UserContext = createContext({
    user: null,
    setUser: (user) => {},
    updateUser: (user) => {},
    logout: () => {}
});

export function UserProvider({ children }) {
    const [user, setUser] = useState(() => {
        // 先从 localStorage 读取用户信息
        if (typeof window !== "undefined") {
            const storedUser = localStorage.getItem("user");
            return storedUser ? JSON.parse(storedUser) : null;
        }
        return null;
    });

    // 检查用户登录状态
    useEffect(() => {
        const storedUser = localStorage.getItem("user"); // 读取 localStorage
        const token = Cookies.get("token"); // 从 Cookies 中获取 token
        const userId = Cookies.get("user_id"); // 从 Cookies 中获取 user_id

        if(storedUser){
            setUser(JSON.parse(storedUser)); // 设置用户状态
        }
        else if (token && userId) {
            axios.get(`/users/${userId}`, {
                headers: { Authorization: `Bearer ${token}` } // 发送带有 token 的请求
            })
            .then((response) => {
                setUser(response.data); // 设置用户状态
                localStorage.setItem("user", JSON.stringify(response.data)); // 存入 localStorage
            })
            .catch(() => {
                setUser(null); // 如果请求失败，重置用户状态
                localStorage.removeItem("user"); // 移除无效数据
            });
        }
    }, []);

    // 更新用户数据时同步到 localStorage
    const updateUser = (newUser) => {
        setUser(newUser);
        if (newUser) {
            localStorage.setItem("user", JSON.stringify(newUser));
        } else {
            localStorage.removeItem("user");
        }
    };

    // 登出方法：清除 Cookies 并重置用户状态
    const logout = () => {
        Cookies.remove("token");
        Cookies.remove("user_id");
        localStorage.removeItem("user"); // 清除存储的数据
        setUser(null);
    };

    return (
        <UserContext.Provider value={{ user, setUser, updateUser, logout }}>
            {children}
        </UserContext.Provider>
    );
}

export function useUser() { // 自定义 hook，用于获取用户状态
    return useContext(UserContext);
}
